<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="phoneNum"
                name="手机号"
                label="手机号"
                placeholder="手机号"
                :rules="[{ required: true, message: '请填写手机号' }]"
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button 
                :disabled="buttonFlag"
                round 
                block 
                type="primary"
                native-type="submit"
            >
                验证手机号
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Ref } from 'vue'
import { docheckphone } from "@/api/register";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from "vue-router";

// 创建一个 选项式 API 中的 this.$router
const router = useRouter()

//存储用户输入手机号
const phoneNum: Ref<string> = ref('')

// 当前计算属性, 会根据用户输入的手机号 决定 按钮能否被点击
const buttonFlag = computed(() => {
    // return false

    return !/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(phoneNum.value)
})

//点击验证手机号
async function onSubmit() {
    const { data } = await docheckphone({
        tel: phoneNum.value
    })

    if (data.code !== '200') {
        // 提示用户手机号已被注册
        return showFailToast(data.message);
    }

    // 提醒用户手机号正确
    showSuccessToast(data.message);

    //临时存储
    window.localStorage.setItem('phoneNum', phoneNum.value)
    
    // 跳转到第二个注册页面
    router.push('/register/no2')
}
</script>